﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;
using QMERP.Infrastructure.Security;

namespace QMERP.Application.Services
{
    public class LogOperateService : ILogOperateService
    {
        private readonly QMERPDbContext _db;
        private readonly IMapper _mapper;
        private readonly ICurrentUser _currentUser;
        public LogOperateService(QMERPDbContext db, IMapper mapper, ICurrentUser currentUser)
        {
            _db = db;
            _mapper = mapper;
            _currentUser = currentUser;
        }
        /// <summary>
        /// 获取操作日志列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageResponse<LogOperateResponse>> Query(PageRequest request)
        {
            PageResponse<LogOperateResponse> model = new();
            var query = _db.LogOperate.OrderByDescending(x => x.LogOn);
            int totalCount = await query.CountAsync();
            List<LogOperate> list = await query.Paging(request.PageIndex, request.PageSize).ToListAsync();
            model.PageIndex = request.PageIndex;
            model.PageSize = request.PageSize;
            model.TotalCount = totalCount;
            model.List = _mapper.Map<List<LogOperateResponse>>(list);
            return model;
        }
        /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task Add(LogOperateAddRequest request)
        {
            var logOperate = _mapper.Map<LogOperate>(request);
            logOperate.UserName = _currentUser.UserName;
            await _db.AddAsync(logOperate);
            await _db.SaveChangesAsync();
        }
    }
}
